package gemini.pollux.ui.client.mvp;

import gemini.pollux.ui.client.mvp.container.PolluxPlaceContainer;
import gemini.pollux.ui.client.mvp.event.ContainerRequestEvent;
import gemini.pollux.ui.client.mvp.event.ContainerRequestHandler;
import gemini.pollux.ui.client.mvp.event.WidgetChangeEvent;
import gemini.pollux.ui.client.page.content.marketingplan.level.LevelPresenter;
import gemini.pollux.ui.client.page.content.product.product.ProductPresenter;
import gemini.pollux.ui.client.page.content.product.producttype.ProductTypePresenter;
import gemini.pollux.ui.client.utils.UIConstants.LayoutPosition;

import java.util.HashMap;

import ch.elca.gwt.mvp.client.EventBus;
import ch.elca.gwt.mvp.client.place.Place;
import ch.elca.gwt.mvp.client.place.PlaceChangedEvent;
import ch.elca.gwt.mvp.client.place.PlaceRequest;
import ch.elca.gwt.mvp.client.widget.WidgetPresenter;

import com.google.inject.Inject;

public class PlaceRequestManager {
	private final EventBus globalEventBus;
	private static HashMap<String, Place> placeMapper = new HashMap<String, Place>();

	@Inject
	public PlaceRequestManager(final EventBus globalEventBus) {
		this.globalEventBus = globalEventBus;
	}

	public void registerHandlers() {
		this.globalEventBus.addHandler(ContainerRequestEvent.getType(),
				new ContainerRequestHandler() {
					@Override
					public void onRequest(final ContainerRequestEvent event) {
						PolluxPlaceContainer<?> newPlace = (PolluxPlaceContainer<?>) getPlace(event.getRequest().getPlace().getId());
						gotoContainerRequestedPlace(event, newPlace);
					}
				});
	}
	
	private void gotoContainerRequestedPlace(final ContainerRequestEvent event,
			final PolluxPlaceContainer<?> requestedPlace) {

		final WidgetPresenter<?> presenter = (WidgetPresenter<?>)requestedPlace.getPresenter();

		if (!presenter.isBound()) {
			presenter.bind();
		}

		globalEventBus.fireEvent(new WidgetChangeEvent(presenter, event.getPosition()));
		
		if (event.getPosition() == null || event.getPosition().equals(LayoutPosition.CONTENT)) {
			globalEventBus.fireEvent(new PlaceChangedEvent(new PlaceRequest(
					presenter.getPlace())));
		}
	}

	private static void intPlaceStore() {
		putPlace(LevelPresenter.PLACE);
		putPlace(ProductTypePresenter.PLACE);
		putPlace(ProductPresenter.PLACE);
    }

    private static void putPlace(final Place place) {
        placeMapper.put(place.getId(), place);
    }

    public static Place getPlace(final String key) {
        if (placeMapper.isEmpty()) {
            intPlaceStore();
        }
        return placeMapper.get(key);
    }
}
